<template>
  <div class="stock-adjust-form">
    <form @submit.prevent="submitForm">
      <!-- 商品信息 -->
      <div class="form-section">
        <h3>商品信息</h3>
        <div class="product-info">
          <div class="product-image">
            <img :src="product.productImage || product.image || '/default-product.png'" :alt="product.productName || product.name">
          </div>
          <div class="product-details">
            <h4 class="product-name">{{ product.productName || product.name || '未命名商品' }}</h4>
            <div class="product-meta">
              <span class="product-code">编码: {{ product.productCode || product.code || '无编码' }}</span>
              <span v-if="product.skuCode" class="product-sku">SKU: {{ product.skuCode }}</span>
            </div>
            <div class="current-stock">
              <span class="stock-label">当前库存:</span>
              <span class="stock-value">{{ product.currentStock || product.stock || 0 }} {{ product.stockUnit || '件' }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 调整类型 -->
      <div class="form-section">
        <h3>调整类型</h3>
        <div class="adjustment-types">
          <label class="type-option">
            <input v-model="form.adjustmentType" type="radio" value="in">
            <div class="type-content">
              <div class="type-icon in">
                <i class="fas fa-plus"></i>
              </div>
              <div class="type-info">
                <div class="type-title">入库调整</div>
                <div class="type-desc">增加库存数量</div>
              </div>
            </div>
          </label>
          
          <label class="type-option">
            <input v-model="form.adjustmentType" type="radio" value="out">
            <div class="type-content">
              <div class="type-icon out">
                <i class="fas fa-minus"></i>
              </div>
              <div class="type-info">
                <div class="type-title">出库调整</div>
                <div class="type-desc">减少库存数量</div>
              </div>
            </div>
          </label>
          
          <label class="type-option">
            <input v-model="form.adjustmentType" type="radio" value="adjust">
            <div class="type-content">
              <div class="type-icon adjust">
                <i class="fas fa-edit"></i>
              </div>
              <div class="type-info">
                <div class="type-title">盘点调整</div>
                <div class="type-desc">直接设置库存数量</div>
              </div>
            </div>
          </label>
        </div>
      </div>

      <!-- 调整数量 -->
      <div class="form-section">
        <h3>调整数量</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>调整数量 *</label>
            <input 
              v-model.number="form.quantity" 
              type="number" 
              min="0" 
              step="1"
              :placeholder="getQuantityPlaceholder()"
              required
            >
            <div class="quantity-info">
              <span class="current-info">当前: {{ product.currentStock || product.stock || 0 }} {{ product.stockUnit || '件' }}</span>
              <span v-if="form.adjustmentType && form.quantity" class="result-info">
                调整后: {{ getResultQuantity() }} {{ product.stockUnit || '件' }}
              </span>
            </div>
          </div>
          <div class="form-group">
            <label>调整原因 *</label>
            <select v-model="form.reason" required>
              <option value="">请选择调整原因</option>
              <option value="采购入库">采购入库</option>
              <option value="销售出库">销售出库</option>
              <option value="盘点调整">盘点调整</option>
              <option value="损耗调整">损耗调整</option>
              <option value="退货入库">退货入库</option>
              <option value="调拨入库">调拨入库</option>
              <option value="调拨出库">调拨出库</option>
              <option value="其他">其他</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 调整详情 -->
      <div class="form-section">
        <h3>调整详情</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>操作员</label>
            <input v-model="form.operator" type="text" placeholder="请输入操作员姓名">
          </div>
          <div class="form-group">
            <label>调整日期时间</label>
            <input 
              v-model="form.adjustmentDate" 
              type="datetime-local"
            >
          </div>
          <div class="form-group full-width">
            <label>备注说明</label>
            <textarea v-model="form.remark" placeholder="请输入备注说明" rows="3"></textarea>
          </div>
        </div>
      </div>

      <!-- 调整预览 -->
      <div v-if="form.adjustmentType && form.quantity" class="form-section">
        <h3>调整预览</h3>
        <div class="adjustment-preview">
          <div class="preview-item">
            <span class="preview-label">调整类型:</span>
            <span class="preview-value">{{ getAdjustmentTypeText() }}</span>
          </div>
          <div class="preview-item">
            <span class="preview-label">调整数量:</span>
            <span class="preview-value" :class="form.adjustmentType">
              {{ getActualAdjustmentQuantity() > 0 ? '+' : '' }}{{ getActualAdjustmentQuantity() }} {{ product.stockUnit || '件' }}
            </span>
          </div>
          <div class="preview-item">
            <span class="preview-label">调整前库存:</span>
            <span class="preview-value">{{ product.currentStock || product.stock || 0 }} {{ product.stockUnit || '件' }}</span>
          </div>
          <div class="preview-item">
            <span class="preview-label">调整后库存:</span>
            <span class="preview-value result">{{ getResultQuantity() }} {{ product.stockUnit || '件' }}</span>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <button type="button" class="btn-cancel" @click="$emit('close')">
          取消
        </button>
        <button type="submit" class="btn-submit" :disabled="!isFormValid">
          <i class="fas fa-save"></i>
          确认调整
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { ref, computed } from 'vue'

export default {
  name: 'StockAdjustForm',
  props: {
    product: {
      type: Object,
      required: true
    }
  },
  emits: ['close', 'success'],
  setup(props, { emit }) {
    // 表单数据
    const form = ref({
      adjustmentType: '',
      quantity: 0,
      reason: '',
      operator: '',
      adjustmentDate: '',
      remark: ''
    })
    
    // 获取当前日期时间（格式化为datetime-local输入格式）
    const getCurrentDateTime = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day}T${hours}:${minutes}`
    }
    
    // 初始化表单时设置默认日期时间
    form.value.adjustmentDate = getCurrentDateTime()
    
    // 获取数量占位符
    const getQuantityPlaceholder = () => {
      switch (form.value.adjustmentType) {
        case 'in':
          return '请输入入库数量'
        case 'out':
          return '请输入出库数量'
        case 'adjust':
          return '请输入调整后库存数量'
        default:
          return '请输入调整数量'
      }
    }
    
    // 获取调整类型文本
    const getAdjustmentTypeText = () => {
      const types = {
        'in': '入库调整',
        'out': '出库调整',
        'adjust': '盘点调整'
      }
      return types[form.value.adjustmentType] || ''
    }
    
    // 获取调整后数量
    const getResultQuantity = () => {
      if (!form.value.adjustmentType || !form.value.quantity) {
        return props.product.currentStock || props.product.stock || 0
      }
      
      const currentStock = props.product.currentStock || props.product.stock || 0
      switch (form.value.adjustmentType) {
        case 'in':
          return currentStock + form.value.quantity
        case 'out':
          return Math.max(0, currentStock - form.value.quantity)
        case 'adjust':
          return form.value.quantity
        default:
          return currentStock
      }
    }
    
    // 表单验证
    const isFormValid = computed(() => {
      return form.value.adjustmentType && 
             form.value.quantity > 0 && 
             form.value.reason &&
             getResultQuantity() >= 0
    })
    
    // 计算实际调整数量（增量）
    const getActualAdjustmentQuantity = () => {
      if (!form.value.adjustmentType || !form.value.quantity) {
        return 0
      }
      
      const currentStock = props.product.currentStock || props.product.stock || 0
      switch (form.value.adjustmentType) {
        case 'in':
          // 入库：直接使用输入的数量
          return form.value.quantity
        case 'out':
          // 出库：使用负数表示减少
          return -form.value.quantity
        case 'adjust':
          // 盘点调整：计算差值
          return form.value.quantity - currentStock
        default:
          return 0
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      try {
        const actualQuantity = getActualAdjustmentQuantity()
        
        const adjustmentData = {
          productId: props.product.id,
          adjustmentType: form.value.adjustmentType,
          quantity: actualQuantity, // 使用计算后的实际调整数量
          reason: form.value.reason,
          operator: form.value.operator || '管理员',
          adjustmentDate: form.value.adjustmentDate || new Date().toISOString(),
          remark: form.value.remark,
          beforeStock: props.product.currentStock || props.product.stock || 0,
          afterStock: getResultQuantity()
        }
        
        // 调用后端API进行库存调整
        const url = `/api/retail/products/${adjustmentData.productId}/adjust-stock?quantity=${actualQuantity}&reason=${encodeURIComponent(adjustmentData.reason)}&operatorName=${encodeURIComponent(adjustmentData.operator)}`
        
        console.log('库存调整数据:', {
          调整类型: form.value.adjustmentType,
          用户输入数量: form.value.quantity,
          实际调整数量: actualQuantity,
          调整前库存: adjustmentData.beforeStock,
          调整后库存: adjustmentData.afterStock,
          请求URL: url
        })
        
        const response = await fetch(url, {
          method: 'POST',
          headers: { 
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.ok) {
          emit('success')
        } else {
          console.error('库存调整失败:', response.statusText)
          alert('库存调整失败，请重试')
        }
      } catch (error) {
        console.error('库存调整失败:', error)
        alert('库存调整失败，请检查网络连接')
      }
    }
    
    return {
      form,
      isFormValid,
      getQuantityPlaceholder,
      getAdjustmentTypeText,
      getResultQuantity,
      getActualAdjustmentQuantity,
      getCurrentDateTime,
      submitForm
    }
  }
}
</script>

<style scoped>
.stock-adjust-form {
  max-width: 600px;
  margin: 0 auto;
}

.form-section {
  background: #f8fafc;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
}

.form-section h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e2e8f0;
}

.product-info {
  display: flex;
  gap: 16px;
  align-items: center;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 16px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  background: #f7fafc;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 1.125rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 4px;
}

.product-meta {
  display: flex;
  gap: 12px;
  margin-bottom: 4px;
}

.product-code,
.product-sku {
  font-size: 0.875rem;
  color: #718096;
}

.current-stock {
  display: flex;
  gap: 8px;
  align-items: center;
}

.stock-label {
  font-size: 0.875rem;
  color: #4a5568;
}

.stock-value {
  font-weight: 600;
  color: #2d3748;
}

.adjustment-types {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.type-option {
  cursor: pointer;
}

.type-option input[type="radio"] {
  display: none;
}

.type-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.type-option input[type="radio"]:checked + .type-content {
  border-color: #43e97b;
  background: #f0fff4;
}

.type-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.type-icon.in {
  background: #48bb78;
}

.type-icon.out {
  background: #f56565;
}

.type-icon.adjust {
  background: #ed8936;
}

.type-info {
  flex: 1;
}

.type-title {
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 2px;
}

.type-desc {
  font-size: 0.875rem;
  color: #718096;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  font-weight: 500;
  color: #4a5568;
  font-size: 0.875rem;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 10px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 0.875rem;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #43e97b;
  box-shadow: 0 0 0 3px rgba(67, 233, 123, 0.1);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.quantity-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 0.875rem;
}

.current-info {
  color: #4a5568;
}

.result-info {
  color: #43e97b;
  font-weight: 500;
}

.adjustment-preview {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 16px;
}

.preview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f1f5f9;
}

.preview-item:last-child {
  border-bottom: none;
}

.preview-label {
  font-weight: 500;
  color: #4a5568;
}

.preview-value {
  font-weight: 600;
  color: #2d3748;
}

.preview-value.in {
  color: #48bb78;
}

.preview-value.out {
  color: #f56565;
}

.preview-value.adjust {
  color: #ed8936;
}

.preview-value.result {
  color: #43e97b;
  font-size: 1.1rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 24px 0;
}

.btn-cancel,
.btn-submit {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-cancel {
  background: #e2e8f0;
  color: #4a5568;
}

.btn-submit {
  background: #43e97b;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-submit:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-cancel:hover,
.btn-submit:hover:not(:disabled) {
  transform: translateY(-1px);
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .product-info {
    flex-direction: column;
    text-align: center;
  }
  
  .type-content {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>
